package cis350.pcr.activities;

import cis350.pcr.types.*;
import cis350.pcr.types.Type.RatingType;
import cis350.pcr.types.Type.SearchType;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeSet;

import cis350.pcr.JSONResult;
import cis350.pcr.R;
import cis350.pcr.SearchHandler;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;

import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the activity that displays the result of Penn Course Review search.
 * @author Perk Jeff Eric Tata
 */
public class ResultActivity extends Activity {

	private String search_term, sortedBy, description, filter, action_title, path;
	private String first_column;
	private ArrayList<String> json_data;
	//private String json_data;
	private ArrayList<String> course_descriptionList;
	private String course_description;
	private SearchType search_type;
	private RatingType[] displayed_ratings = {RatingType.CourseQuality, RatingType.InstructorQuality, RatingType.Difficulty};
	private int sortDirection = 1;
	private boolean average = true; // true = average, false = most recent
	private ArrayList<String> semester_label, semester_data;
	private SearchHandler handler;
	private Item[] resultArray;

	PopupMenu popup;
	ActionBar actionBar;

	// /// COLORS /////
	int textColor, columnDeSelectedColor, columnSelectedColor;

	// *****Method 1*****
	/**
	 * This method is called when the Activity is launched to create the various
	 * parts of the displayed activity.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.result);
		
		// retrieve data from previous views
		getExtras();
		setColors();
		// initialize action bar
		actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setIcon(R.drawable.mag);

		// sets button listeners
		setButtonClickListeners();
		
		showInitialResults();
		Log.d("search_term", search_term);
		Log.d("Search type", search_type.toString());
	}

	private void setColors() {
		textColor = getResources().getColor(R.color.text_color);
		columnSelectedColor = getResources().getColor(R.color.col_selected);
		columnDeSelectedColor = getResources().getColor(R.color.col_deselected);
	}

	private void getExtras() {
		Intent i = getIntent();
		search_term = i.getStringExtra("search input");
		
		path = i.getStringExtra("path");
		json_data = SearchHandler.json_data;
		course_descriptionList = i.getStringArrayListExtra("description");
		if (course_descriptionList != null && course_descriptionList.size() > 0)
			course_description = course_descriptionList.get(course_descriptionList.size()-1);
		
		search_type = (SearchType) i.getSerializableExtra("search type");
		filter = i.getStringExtra("filter");
		action_title = i.getStringExtra("action title");
		semester_data = i.getStringArrayListExtra("semester data");
		semester_label = i.getStringArrayListExtra("semester label");
	}

	private void setButtonClickListeners() {
		Button first = (Button)findViewById(R.id.first);
		first.setOnLongClickListener(onFirstLongClick);
		
	    Button second = (Button)findViewById(R.id.second);
	    second.setOnLongClickListener(onSecondLongClick);
	    
	    Button third = (Button)findViewById(R.id.third);
	    third.setOnLongClickListener(onThirdLongClick);
	    
	    Button fourth = (Button)findViewById(R.id.fourth);
	    fourth.setOnLongClickListener(onFourthLongClick);	
	}

	// *****Method 2*****
	/**
	 * This method is used to extract information out of the JSON
	 * object returned. When the information is extracted, the relevant
	 * methods are called to update the fields.
	 */
	private void showInitialResults() { 
		JSONResult json_result = new JSONResult(semester_data, semester_label);
		json_result.parse(json_data, course_description, search_type, filter);
		Item result = json_result.result;
		if(!action_title.equals(""))
			action_title += " > ";
		action_title += result.getActionBarTitle();
		String avg_course = getScore(json_result.all_ratings, RatingType.CourseQuality);
		String avg_instr = getScore(json_result.all_ratings, RatingType.InstructorQuality);
		String avg_diff = getScore(json_result.all_ratings, RatingType.Difficulty);

		// put title in action bar
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_HOME_AS_UP);
		actionBar.setTitle(action_title);
		
		// add description if its a course
		description = result.getInfo();
		//some courses have no description
		if ("".equals(description))
			description = "This course has no description";
		
		createRatingRow(avg_course, avg_instr, avg_diff);

		// creates each row
		resultArray = json_result.map.values().toArray(new Item[0]);
		switch(search_type){
		case COURSE:
			first_column = getResources().getStringArray(R.array.first_course)[0];
			break;
		case COURSE_INSTR:
			first_column = getResources().getStringArray(R.array.first_course_instr)[0];
			break;
		case INSTRUCTOR:
			first_column = getResources().getStringArray(R.array.first_instructor)[0];
			break;
		case DEPT:
			first_column = getResources().getStringArray(R.array.first_dept)[0];
			break;
		case INSTR_COURSE:
			first_column = getResources().getStringArray(R.array.first_instr_course)[0];
			break;
		}
		onFirstSortClick(null);
	}

	// *****Method 3*****
	/**
	 * This method changes how the course reviews of each instructor are sorted.
	 * 'rtd' changes the number the table should display as a rating, null
	 * will cause the current display to remain.
	 * @param r1 String
	 * @param sortBy String
	 */
	private void sortAndPrintBy(RatingType r, Integer col, String sortBy) {
		if(r != null && col != null)
			displayed_ratings[col] = r;
		setSortButtonText();
		sortedBy = sortBy;
		sortDirection *= -1;
		TableLayout tl = (TableLayout) findViewById(R.id.tableLayout2);
		tl.removeAllViews();

		if (sortedBy.equals("Instructor")) {
			Arrays.sort(resultArray, new Comparator<Item>() {

				public int compare(Item item1, Item item2) {
					return (sortDirection)*(((Instructor) item1).lastName.compareToIgnoreCase(((Instructor) item2).lastName));
				}
			});
		} else if (sortedBy.equals("Most Recent")) {
			Arrays.sort(resultArray, new Comparator<Item>() {

				public int compare(Item item1, Item item2) {
					String semes1 = item1.ratings.first().id;
					String semes2 = item2.ratings.first().id;
					return (sortDirection)*(semes2.compareTo(semes1));
				}
			});
		} else if (sortedBy.equals("No. Responses")) {
			Arrays.sort(resultArray, new Comparator<Item>() {

				public int compare(Item item1, Item item2) {
					Integer resp1 = Integer.valueOf(item1.ratings.first().num_reviewers);
					Integer resp2 = Integer.valueOf(item2.ratings.first().num_reviewers);
					return (sortDirection)*(resp1.compareTo(resp2));
				}
			});
		} else if (sortedBy.equals("Course Number")) {
			Arrays.sort(resultArray, new Comparator<Item>() {

				public int compare(Item item1, Item item2) {
					String course1 = item1.name;
					String course2 = item2.name;
					return (sortDirection)*(course1.compareTo(course2));
				}
			});
		} else if (sortedBy.equals("rating1")) {
			Arrays.sort(resultArray, new Comparator<Item>() {

				public int compare(Item item1, Item item2) {
					String rating1 = getScore(item1.ratings, displayed_ratings[0]);
					String rating2 = getScore(item2.ratings, displayed_ratings[0]);
					return (sortDirection)*(rating1.compareTo(rating2));
				}
			});
		} else if (sortedBy.equals("rating2")) {
			Arrays.sort(resultArray, new Comparator<Item>() {

				public int compare(Item item1, Item item2) {
					String rating1 = getScore(item1.ratings, displayed_ratings[1]);
					String rating2 = getScore(item2.ratings, displayed_ratings[1]);
					return (sortDirection)*(rating1.compareTo(rating2));
				}
			});
		} else if (sortedBy.equals("rating3")) {
			Arrays.sort(resultArray, new Comparator<Item>() {

				public int compare(Item item1, Item item2) {
					String rating1 = getScore(item1.ratings, displayed_ratings[2]);
					String rating2 = getScore(item2.ratings, displayed_ratings[2]);
					return (sortDirection)*(rating1.compareTo(rating2));
				}
			});
		}
		boolean even = true;
		for (Item item : resultArray) {
			even = even == true ? false : true;		
			createTableRow(item, even);
		}
	}

	private String getScore(TreeSet<Semester> all_ratings, RatingType type) {
		double result = 0.0;
		if (average) {
			double sum = 0;
			for (Semester s : all_ratings){
				if(s.get(type) == null){
					result = -1;
					break;
				}
				sum += s.get(type).doubleValue();
			}
			if(result != -1)
				result = sum/((double) all_ratings.size());
		} else
			result = all_ratings.first().get(type).doubleValue();
		if(result == -1)
			return "N/A";
		return String.format("%.2f", result);
		
	}

	//*****Method 4*****
	/**
	 * This method is responsible in creating each row in the table that
	 * displays the instructor reviews. Each row contains information
	 * about the name of the instructor, the semester ID, a rating and a color
	 * coding.
	 * @param row_text String
	 * @param row_subtext String
	 * @param r1 String
	 * @param ratingColor Integer
	 * @param filter String
	 */
	private void createTableRow(final Item item, boolean even) {
		final String row_text = item.getRowText();
		String row_subtext = item.getRowSubtext(average);
		final String filter = item.name; 
		String[] rats = new String[displayed_ratings.length];
		for (int n = 0; n < displayed_ratings.length; n++)
			rats[n] = getScore(item.ratings, displayed_ratings[n]);
		
		TableLayout tl = (TableLayout) findViewById(R.id.tableLayout2);

		final Context activity = this;
		TableRow tr = new TableRow(this);
		tr.setClickable(true);
		tr.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				SearchType temp_type = search_type == SearchType.INSTRUCTOR ? SearchType.INSTR_COURSE
						: search_type == SearchType.COURSE ? SearchType.COURSE_INSTR
								: SearchType.COURSE;
				switch(search_type){
				case DEPT:
					handler = new SearchHandler(activity);
					String code = handler.codeDB.getCourse(filter).get(0).split(",")[0];
					handler.search("coursehistories/" + code + "/reviews", filter, temp_type, "none");
					return;
				case INSTR_COURSE:
				case COURSE_INSTR:
					showRatings(item, row_text);
					return;
				}

				Intent nextScreen = new Intent(getApplicationContext(),
						ResultActivity.class);
				nextScreen.putExtra("search input", search_term);
				nextScreen.putExtra("search type", temp_type);
				nextScreen.putExtra("filter", filter);
				nextScreen.putExtra("description", course_descriptionList);
				nextScreen.putExtra("action title", action_title);
				nextScreen.putExtra("semester label", semester_label);
				nextScreen.putExtra("semester data", semester_data);
				nextScreen.putExtra("path", path);

				startActivity(nextScreen);
			}
		});
		tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		if (even == true)
			tr.setBackgroundColor(getResources().getColor(R.color.even));
		else
			tr.setBackgroundColor(getResources().getColor(R.color.odd));
		tr.setGravity(Gravity.CENTER);

		// professor name
		TextView rowtext = new TextView(this);
		rowtext.setText(row_text);
		rowtext.setTextSize(15);
		rowtext.setTextColor(textColor);

		// semester
		TextView rowsubtext = new TextView(this);
		rowsubtext.setText(row_subtext);
		rowsubtext.setTextSize(10);
		rowsubtext.setTextColor(textColor);

		LinearLayout ll = new LinearLayout(this);
		ll.setOrientation(LinearLayout.VERTICAL);
		ll.setPadding(10, 10, 0, 10);

		ll.addView(rowtext, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		if(!row_subtext.equals(""))
			ll.addView(rowsubtext, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

		TextView[] ratings = new TextView[displayed_ratings.length];
		for (int n = 0; n < displayed_ratings.length; n++){
			ratings[n] = new TextView(this);
			ratings[n].setText(rats[n]);
			ratings[n].setTextColor(textColor);
			ratings[n].setGravity(Gravity.RIGHT);
			ratings[n].setTextSize(15);
			ratings[n].setPadding(30, 0, 30, 0);
		}

		tr.addView(ll, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f));
		for (TextView tv : ratings)
			tr.addView(tv, new TableRow.LayoutParams());
		tl.addView(tr, new TableLayout.LayoutParams());
	}

	protected void showRatings(Item item, String row_text) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Course Ratings: " + row_text);
		String[] list = getResources().getStringArray(R.array.rating_array);
		for(int i = 0; i < list.length; i++){
			RatingType temp = RatingType.values()[i];
			list[i] += ": "+ item.ratings.first().get(temp);				
		}
		builder.setItems(list, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,
					int item) {
			}
		});		
		builder.show();
	}

	// *****Method 5*****
	/**
	 * This method creates a drop down menu from the action bar which displays
	 * options for the user to select. When the options are selected,
	 * the course reviews are sorted based on what is selected.
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in action bar clicked; go home
			Intent intent = new Intent(this, SearchActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;		
		case R.id.menu_info:
			Log.v("menu", "clicked");
			AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
			if(description == null || "".equals(description.trim()))
				description = "There is no course information available.";
			builder1.setMessage("Course description:\n\n" + description)
			       .setCancelable(true)
			       .setNegativeButton("Close", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			// use builder.create() to create the dialog before showing it
			builder1.show();			
			return true;
		case R.id.menu_help:
			Log.v("menu", "clicked");
			AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
			builder2.setMessage(R.string.help)
					.setCancelable(true)
					.setNegativeButton("Close",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			// use builder.create() to create the dialog before showing it
			builder2.show();
			return true;
		case R.id.menu_settings:
			Intent nextScreen = new Intent(getApplicationContext(),
					SettingsActivity.class);
			startActivity(nextScreen);
			return true;
		case R.id.menu_back:
			super.onBackPressed();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * This method creates a row to display the average ratings for the course.
	 */
	public void createRatingRow(String cq, String iq, String diff) {
		/* Find Tablelayout defined in main.xml */

		final TextView tv5 = (TextView) findViewById(R.id.toggle_average);
		tv5.setText(">Average");
		tv5.setTextSize(15);
		tv5.setTextColor(textColor);
		
		final TextView tv4 = (TextView) findViewById(R.id.toggle_ratings);
		tv4.setText(">Most Recent");
		tv4.setTextColor(textColor);
		tv4.setTextSize(8);
		
		tv5.setOnClickListener(new View.OnClickListener() {
		
			public void onClick(View v) {
				if(tv5.getText().toString().equals(">Average")){
				tv5.setText(">Most Recent");
				tv4.setText("Average");
				
				}
				else {
					tv5.setText(">Average");
					tv4.setText("Most Recent");
				}
				Context context = getApplicationContext();
				String text = "";
				average = !average;
				if(average)
					text = "Displaying average ratings";
				else
					text = "Displaying most recent semester ratings";
				int duration = Toast.LENGTH_LONG;
				Toast.makeText(context, text, duration).show();
				sortAndPrintBy(null, null, sortedBy);
				
			}
		});

		tv4.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(tv4.getText().toString().equals("Average")){
				tv4.setText("Most Recent");
				tv5.setText(">Average");
				}
				else {
					tv4.setText("Average");	
					tv5.setText(">Most Recent");
				}
				Context context = getApplicationContext();
				String text = "";
				average = !average;
				if(average)
					text = "Displaying average ratings";
				else
					text = "Displaying most recent semester ratings";
				int duration = Toast.LENGTH_LONG;
				Toast.makeText(context, text, duration).show();
				sortAndPrintBy(null, null, sortedBy);
			}
		});
		
		TextView tv1 = (TextView) findViewById(R.id.course);
		tv1.setText(cq);
		tv1.setTextColor(textColor);

		TextView tv2 = (TextView) findViewById(R.id.instructor);
		tv2.setText(iq);
		tv2.setTextColor(textColor);

		TextView tv3 = (TextView) findViewById(R.id.difficulty);
		tv3.setText(diff);
		tv3.setTextColor(textColor);

		/*TableLayout tl = (TableLayout) findViewById(R.id.tableLayout3);

		// add line
		View v = new View(this);
		v.setBackgroundColor(textColor);
		tl.addView(v, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 2));*/
	}
	
	/**
	 * This configures the bottom search buttons to display
	 * the correct value when different sorts are applied.
	 */
	private void setSortButtonText() {
		Resources res = getResources();
		String[] text = res.getStringArray(R.array.rating_array);
		int[] nums = new int[displayed_ratings.length];
		for (int n = 0; n < displayed_ratings.length; n++)
			nums[n] = displayed_ratings[n].ordinal();
		((Button) findViewById(R.id.first)).setText(first_column);
		((Button) findViewById(R.id.second)).setText(text[nums[0]]);
		((Button) findViewById(R.id.third)).setText(text[nums[1]]);
		((Button) findViewById(R.id.fourth)).setText(text[nums[2]]);
	}
	
	/**
	 * Create action bar.
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.action_result, menu);
		return true;
	}
	
	/**
	 * Capitalize strings correctly.
	 * @param str String
	 * @return String
	 */
	public static String capitalize(String str){
		StringBuffer sb = new StringBuffer(str.toLowerCase().trim());
		String[] arr = { " ", "-", "/", "&", "\"", "\'", "\\(" };
		if (str.length() == 0)
			return "";
		for (int n = 0; n < sb.length(); n++) {
			if (sb.charAt(n) < 32 || sb.charAt(n) > 126)
				sb.deleteCharAt(n);
		}
		for (String d : arr) {
			String[] split = sb.toString().split(d);
			sb = new StringBuffer();
			for(int n = 0; n < split.length; n++){
				if(split[n].length() == 0)
					continue;
				String t = split[n].toUpperCase();
				if(t.equals("I")||t.equals("II")||t.equals("III")||t.equals("IV")||t.equals("V"))
					sb.append(t);
				else{
					char[] c = split[n].toCharArray();
					c[0] = Character.toUpperCase(c[0]);
					sb.append(new String(c));
				}
				if(split[n].length() == 1 && n != split.length-1){
					if(Character.isLetter(split[n].charAt(0)))
						sb.append(".");
				}
				sb.append(d);
			}
		}
		return sb.toString().substring(0, sb.length()-arr.length);
	}

	private OnLongClickListener onFirstLongClick = new OnLongClickListener() {
	    public boolean onLongClick(View v) {
	    	select("first");
	    	showFirstColPopup();
			return true;
	    }
	};
	
	private OnLongClickListener onSecondLongClick = new OnLongClickListener() {
	    public boolean onLongClick(View v) {
	    	select("second");
	    	showRatingPopup(0);
			return true;
	    }
	};
	
	private OnLongClickListener onThirdLongClick = new OnLongClickListener() {
	    public boolean onLongClick(View v) {
	    	select("third");
	    	showRatingPopup(1);
			return true;
	    }
	};
	
	private OnLongClickListener onFourthLongClick = new OnLongClickListener() {
	    public boolean onLongClick(View v) {
	    	select("fourth");
	    	showRatingPopup(2);
			return true;
	    }
	};
	
	private void showRatingPopup(final int col){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choosing rating to display");
		builder.setItems(R.array.rating_array,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						switch (item) {
						case 0:
							sortAndPrintBy(RatingType.AmountLearned, col, sortedBy);
							break;
						case 1:
							sortAndPrintBy(RatingType.CommAbility, col,
									sortedBy);
							break;
						case 2:
							sortAndPrintBy(RatingType.CourseQuality, col, sortedBy);
							break;
						case 3:
							sortAndPrintBy(RatingType.Difficulty, col, sortedBy);
							break;
						case 4:
							sortAndPrintBy(RatingType.InstructorAccess, col, sortedBy);
							break;
						case 5:
							sortAndPrintBy(RatingType.InstructorQuality, col, sortedBy);
							break;
						case 6:
							sortAndPrintBy(RatingType.ReadingsValue, col, sortedBy);
							break;
						case 7:
							sortAndPrintBy(RatingType.RecommendMajor, col,
									sortedBy);
							break;
						case 8:
							sortAndPrintBy(RatingType.RecommendNonMajor, col,
									sortedBy);
							break;
						case 9:
							sortAndPrintBy(RatingType.StimulateInterest, col, sortedBy);
							break;
						case 10:
							sortAndPrintBy(RatingType.WorkRequired, col,
									sortedBy);
							break;
						}
					}
				});
		builder.show();
	}
	
	protected void showFirstColPopup() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Change column");
		switch(search_type){
		case COURSE:
			builder.setItems(R.array.first_course,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {
							Button b = (Button) findViewById(R.id.first);
							first_column = getResources().getStringArray(
									R.array.first_course)[item];
							b.setText(first_column);
						}
					});
			break;
		case COURSE_INSTR:
			builder.setItems(R.array.first_course_instr,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {
							Button b = (Button) findViewById(R.id.first);
							first_column = getResources().getStringArray(
									R.array.first_course_instr)[item];
							b.setText(first_column);
						}
					});
			break;
		case INSTRUCTOR:
			builder.setItems(R.array.first_instructor,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {
							Button b = (Button) findViewById(R.id.first);
							first_column = getResources().getStringArray(
									R.array.first_instructor)[item];
							b.setText(first_column);
						}
					});
			break;
		case INSTR_COURSE:
			builder.setItems(R.array.first_instr_course,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {
							Button b = (Button) findViewById(R.id.first);
							first_column = getResources().getStringArray(
									R.array.first_instr_course)[item];
							b.setText(first_column);
						}
					});
			break;
		case DEPT:
			builder.setItems(R.array.first_dept,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {
							Button b = (Button) findViewById(R.id.first);
							first_column = getResources().getStringArray(
									R.array.first_dept)[item];
							b.setText(first_column);
						}
					});
			break;
		}
		

		builder.show();

	}

	/**
	 * Method for left button. Sorts the reviews
	 * according to its value.
	 * @param view View
	 */
	public void onFirstSortClick(View v) {
		select("first");
		sortAndPrintBy(null, null, first_column);
	}
	
	/**
	 * Method for middle button. Sort the reviews according
	 * to its value.
	 * @param view View
	 */
	public void onSecondSortClick(View view) {
		select("second");
		sortAndPrintBy(null, null, "rating1");
	}

	/**
	 * Method for right button. Sort the reviews according
	 * to its value.
	 * @param view View
	 */
	public void onThirdSortClick(View view) {
		select("third");
		sortAndPrintBy(null, null, "rating2");
	}
	
	public void onFourthSortClick(View view) {
		select("fourth");
		sortAndPrintBy(null, null, "rating3");
	}
	
	private void select(String selected) {
		Button first = (Button) findViewById(R.id.first);
		Button second = (Button) findViewById(R.id.second);
		Button third = (Button) findViewById(R.id.third);
		Button fourth = (Button) findViewById(R.id.fourth);
		first.setBackgroundColor(columnDeSelectedColor);
		second.setBackgroundColor(columnDeSelectedColor);
		third.setBackgroundColor(columnDeSelectedColor);
		fourth.setBackgroundColor(columnDeSelectedColor);
		if(selected.equals("first"))
			first.setBackgroundColor(columnSelectedColor);
		else if(selected.equals("second"))
			second.setBackgroundColor(columnSelectedColor);
		else if(selected.equals("third"))
			third.setBackgroundColor(columnSelectedColor);
		else if(selected.equals("fourth"))
			fourth.setBackgroundColor(columnSelectedColor);
	}

	/**
	 * If course description is unable to be obtained,
	 * return a toast that says cannot load course description.
	 */
	public void searchFailed() {
		Context context = getApplicationContext();
		CharSequence text = "Could not load course description.";
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
	}

	/**
	 * To be implemented when needed.
	 * @param response String
	 */
	public void searchSucceeded(String response) {
		// TODO Auto-generated method stub
	}
	@Override
	public void onBackPressed() {
		if (handler != null) {
			if (handler.loadingDialog != null
					&& handler.loadingDialog.isShowing()) {
				handler.loadingDialog.dismiss();
				return;
			}
		}
		super.onBackPressed();
	}

	
}
